package com.mcxx.modules.system.controller;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.system.service.StatisticsExportService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.system.dto.StatisticsExportDTO;
import com.mcxx.modules.system.param.StatisticsExportItemParam;
import com.mcxx.modules.system.param.StatisticsExportParam;
import com.mcxx.modules.system.service.read.StatisticsExportItemReadService;
import com.mcxx.modules.system.service.read.StatisticsExportReadService;
import com.mcxx.service.DefaultRestService;
import com.yinhai.ta404.core.restservice.annotation.RestService;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.validate.annotation.V;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


@Validated
@Api("数据管理/台账")
@RestService({"dataManage/statistics/v2"})
public class StatisticsExportController extends DefaultRestService {

    private final static Logger logger = LoggerFactory.getLogger(StatisticsExportController.class);

    @Autowired
    private StatisticsExportReadService statisticsExportReadService;
    @Autowired
    private StatisticsExportItemReadService statisticsExportItemReadService;
    @Autowired
    private StatisticsExportService statisticsExportService;
    @Autowired
    private FileService fileService;


    @PostMapping("statisticsList")
    @ApiOperation("台账生成列表页")
    public void statisticsList(StatisticsExportParam statisticsExportParam, PageParam pageParam) {
        logger.info("台账生成列表页,参数：{}", statisticsExportParam);
        Page page = statisticsExportReadService.getPage(statisticsExportParam, pageParam, getCurUserAccount());
        setPageBean(page);
        logger.info("台账生成列表页，结果:{}", page);
    }


    @PostMapping("createStatistics")
    @ApiOperation("创建台账")
    public void createStatistics(StatisticsExportDTO statisticsExportDTO){
        logger.info("创建台账,参数：{}");
        statisticsExportService.createStatistics(statisticsExportDTO, getCurUserAccount());
        logger.info("创建台账,结果：{}");
    }


    @PostMapping("getStatisticsDetail")
    @ApiOperation("查看台账详情")
    public void getStatisticsDetail(StatisticsExportItemParam statisticsExportItemParam, PageParam pageParam){
        logger.info("查看台账详情,参数：{}");
        Page page = statisticsExportItemReadService.getPage(statisticsExportItemParam, pageParam);
        setPageBean(page);
        logger.info("查看台账详情,结果：{}");
    }


    @PostMapping("confirmStatistics")
    @ApiOperation("确认台账")
    public void confirmStatistics(HttpServletResponse response, @V("notnull") String statisticId, String objectType){
        logger.info("确认台账,参数：{}");
        statisticsExportService.confirmStatistics(response, statisticId, objectType);
        logger.info("确认台账,结果：{}");
    }


    @PostMapping("deleteStatistics")
    @ApiOperation("删除台账")
    public void deleteStatistics(@RequestPart @V("notnull") List<String> idList){
        logger.info("删除台账,参数：{}");
        statisticsExportService.deleteStatistics(idList);
        logger.info("删除台账,结果：{}");
    }


    @RequestMapping("downStatisticsFile")
    public void downStatisticsFile(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String objectFileId = request.getParameter("objectFileId");
        if(StringUtils.isBlank(objectFileId)) {
            throw new BizException("-1", "还未生成台账文件，请先生成台账文件再进行下载");
        }
        try {





            byte[] content = fileService.download(objectFileId);
            InputStream inputStream = new ByteArrayInputStream(content);
            OutputStream outputStream = response.getOutputStream();

            response.setContentType("application/zip");
          //  response.setHeader("Content-Disposition", String.format("attachment; filename=1.zip"));
            response.setCharacterEncoding("UTF-8");
            response.setContentLength(content.length);
            response.addHeader("Content-Disposition", String.format("attachment; filename=abc.zip"));

            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            setError("下载失败!");
            setSuccess(false);
        }
    }

}
